/**
 * 
 */
package geometry;

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;

/**
 * A LineSeg is a line function with two end points.
 * 
 * @author wu wei
 * 
 */
public class LineSegment extends LineFunction {
	private Point2D.Double endPoint1, endPoint2;
	private Line2D.Double seg;

	/**
	 * @param p1
	 * @param p2
	 * @throws NotDefinedException
	 */
	public LineSegment(Double p1, Double p2) throws NotDefinedException {
		super(p1, p2);
		this.endPoint1 = p1;
		this.endPoint2 = p2;
		this.seg = new Line2D.Double(p1, p2);
	}

	/**
	 * @return the endPoint1
	 */
	public Point2D.Double getEndPoint1() {
		return endPoint1;
	}

	/**
	 * @return the endPoint2
	 */
	public Point2D.Double getEndPoint2() {
		return endPoint2;
	}

	/**
	 * @return a Line2D.Double representation of this line segment.
	 */
	public Line2D.Double asLine2DDouble() {
		return this.seg;
	}

	public boolean doesIntersect(LineFunction lf) {
		Intersection ip = super.intersects(lf);
		if (ip != null) {
			double xmin = Math.min(this.endPoint1.x, this.endPoint2.x);
			double xmax = Math.max(this.endPoint1.x, this.endPoint2.x);
			double ymin = Math.min(this.endPoint1.y, this.endPoint2.y);
			double ymax = Math.max(this.endPoint1.y, this.endPoint2.y);
			if (ip.getX() >= xmin - tinyVal && ip.getX() <= xmax + tinyVal
					&& ip.getY() >= ymin - tinyVal
					&& ip.getY() < ymax + tinyVal) {
				return true;
			}
		}

		return false;
	}

	public Intersection intersects(LineFunction lf) {
		if (this.doesIntersect(lf)) {
			return super.intersects(lf);
		}
		return null;
	}

	public boolean doesIntersectWithLine2D(Line2D.Double l2d) {
		return this.seg.intersectsLine(l2d);
	}

}
